NOTE

1.6 Redis Pub/Sub

What Redis Pub/Sub is, basic publish/subscribe usage, unsubscribe behavior, and pattern matching.

Redis / CacheCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is Redis Pub/Sub?

A publisher puts messages into a channel, and multiple subscribers can subscribe to that channel. It is similar to the publish-subscribe model in Message Queue Introduction and decouples the publisher and subscribers.

2. Redis Pub/Sub Usage

2.1. Basic Usage

PUBLISH
SUBSCRIBE
UNSUBSCRIBE
  • Subscriber 1 subscribes to channels.
127.0.0.1:6379> SUBSCRIBE foo bar
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "foo"
3) (integer) 1
1) "subscribe"
2) "bar"
3) (integer) 2
  • Subscriber 2 subscribes to channels.
127.0.0.1:6379> SUBSCRIBE foo bar
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "foo"
3) (integer) 1
1) "subscribe"
2) "bar"
3) (integer) 2
  • The publisher publishes to channels.
127.0.0.1:6379> PUBLISH foo hahaha
(integer) 2
127.0.0.1:6379> PUBLISH bar jiejiej
(integer) 2
127.0.0.1:6379>
  • Subscribers 1 and 2 receive the messages.
127.0.0.1:6379> SUBSCRIBE foo bar
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "foo"
3) (integer) 1
1) "subscribe"
2) "bar"
3) (integer) 2
1) "message"
2) "foo"
3) "hahaha"
1) "message"
2) "bar"
3) "jiejiej"
  • Subscriber 1 unsubscribes.
UNSUBSCRIBE foo bar
  • When the publisher publishes a message, only subscriber 2 receives it.
  • Subscriber 3 subscribes to a channel and does not receive earlier messages.
127.0.0.1:6379> SUBSCRIBE foo bar
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "foo"
3) (integer) 1
1) "subscribe"
2) "bar"
3) (integer) 2

2.2. Pattern Matching

  • Syntax test:
PSUBSCRIBE news.*
PUNSUBSCRIBE news.*
  • If a subscriber subscribes to a channel both in the basic form and through pattern matching, it receives duplicate messages afterward.
SUBSCRIBE foo
PSUBSCRIBE f*

3. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub